using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json.Serialization;
using Sustainalytics.ESGRatings.DataContract;
using Sustainalytics.ESGRatings.DataContract.Governance;


namespace Sustainalytics.ESGComputing.Service.Tests.GovernanceUnitTests
{
    public class GovernanceHttpClient : HttpClient
    {
        private const string SutLink = "http://localhost:10280/esgcomputingserv/api/v1";

        private static readonly JsonMediaTypeFormatter JsonMediaTypeFormatter = new JsonMediaTypeFormatter
        {
            SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() }
        };

        private readonly HttpClient _sutClient;

        public GovernanceHttpClient()
        {
            _sutClient = new HttpClient();
        }


        public Task<HttpResponseMessage> PostAsync(GovernanceDataContainer dataSet)
        {
            return _sutClient.PostAsync(string.Format("{0}{1}", SutLink, "/dataprovisioning/governancesets"), dataSet,
                JsonMediaTypeFormatter);

        }

        public GovernanceRatingsDto GetComputationResult(Guid setId, Guid matrixId)
        {

            _sutClient.Timeout = new TimeSpan(0, 0, 10, 0);

            var result = _sutClient.PostAsync(string.Format("{0}{1}", SutLink, "/governancecompute"),
                   new GovernanceRatingOptionDto { SetId = setId, MatrixId = matrixId }, JsonMediaTypeFormatter);

            if (result.Result.IsSuccessStatusCode)
            {
                return
                    result.Result.Content.ReadAsAsync<GovernanceRatingsDto>(JsonMediaTypeFormatter.Yield()).Result;

            }
            else
            {
                throw new Exception(
                    result.Result.Content.ReadAsAsync<ErrorModel>(JsonMediaTypeFormatter.Yield())
                        .Result.ErrorMessage);
            }





        }

        public Task<HttpResponseMessage> DeleteAsync(Guid setId)
        {
            var builder = new UriBuilder(string.Format("{0}{1}", SutLink, "/dataprovisioning/governancesets/"));
            var query = HttpUtility.ParseQueryString(builder.Query);
            query["setId"] = setId.ToString();
            builder.Query = query.ToString();
            var url = builder.ToString();

            return _sutClient.DeleteAsync(url);


        }
    }
}